--------------------------------------------------
-- Episode code for every level
-- Created 20:51 2021-1-28
--------------------------------------------------


--[[ TO-DO:
	- [?] Implement anti-cheese for the restart function in the pause menu
		- [ ] Save the player's amount of coins and current power-up state at a checkpoint.
			- [ ] When restarting, set the amount of coins & power-up state to that saved point
				- Unless the player is weaker than the power-up state, then just don't set it
		- [x] ALTERNATIVELY: Make the restart function cost however many coins it costs to die.


	- [ ] Add the SMB2 Super Jump as an upgrade
		

	- [ ] Fix Pichu's position on pause screen when entering the levels menu
		- Just use the Y offset that uses?

	- [ ] Cut down on lag, someone on the forums was complaining about it.
		- [ ] Seperate the door-stuff into a library, then use that on the hub world and any levels that need it.
		- [ ] Mario Castle's luna.lua has massive lag, especially onTick.
			- [x] Have stuff like costume changer only apply if costume changer is actually active.
			- [x] Have layers for the shop stuff only change if there's been a state change. Use a function to call all of it.

	- [ ] Water level transition, where mario dips into the bottom of the level, and teleports into the water level.
		- Like this: https://youtu.be/1OLcCM2zZJE?t=892

	- [ ] Redesign the checkpoints, make it look like this: https://youtu.be/1OLcCM2zZJE?t=184
		- [ ] Also have a SMB3 exit place, but have the exit at the top of the level, with the player most likely to end up at the bottom at first.

	- [ ] Add more ice flowers.
		- [ ] Put them in some of the secondary areas, like the ones w/ stars in them.

	- [ ] Second star in Koopa Mayhem is 8-bit themed

	- [ ] Problem with Boom Boom: If player is standing right on the boss as they die, the orb is spawned and the player immediately collects it.
		- Level *is* counted as beaten, though...

	- [ ] I think I didn't fix how characters are saved in multiplayer; should probably fix that.

	- [ ] Have some desert levels use quicksand, to more warrant the use of an upgrade for the liquid shoes

	- [ ] Re-do SML2 level to be themed around the woods instead

	- [ ] Don't let player use reserve item when currently exiting a level, or when dying.

	- [ ] Check the changes made to the power-up guard system thing, maybe find a way to force the poof effect to work from Big -> Small.

	- [ ] IDEA FOR LIQUID BOOTS: Allow lava upgrade via the shop
		- [ ] Also make it so there's an upgrade for quicksand, at 200 coins
		- [ ] 500 coins for lava upgrade
		- [ ] Timer would be like, 3 seconds at most.

	- [ ] FOR DESERT WORLD: Switch between the windy ambiance version of the track and non-windy using Audio.getMusicPos() and Audio.setMusicPos()

	- [ ] World 3 secret level idea: Windows XP themed level. Because why not.
		- [ ] Place a secret block in the Technology Shores level

	- [ ] Try out the achivement system, mainly for silly things
		- [ ] Make an achivement for freeing all the munchers in the second ice level

	- [ ] Idea: Create HP bar for bosses at the bottom/top of the screen

	- Hidden red coin mission in New Carved Woodlands, or some other level.
		- Going to the waterfalls area, you can find a red ? block, pressing it will activate a time-based red coin mission
		- Implement a GUI for the timer.

	- [x] Have second boom-boom fight go off like how the old toad town thing did it; there's an egg in the middle of the arena, breaking it spawns the boss.
	- [ ] Also modify the boss behavior; try re-creating the winged boom boom? Make it the second phase.

	- [ ] Idea: Beating levels in hard mode earns you the hard mode emblem for the stage
		- [ ] idk what this would serve though, other than a "hey you did this thing" pat on the back
		- [ ] i'd also need to make an animation indicating that the player did the thing and got the emblem, making it obvious something happened
			- [ ] i'd also need to have the icon hover above the doors, preferably only when hard mode is enabled

	- [?] EASTER EGGS
		- [x] Use GameData to make certain things last until file is exited, like:
			- [x] type "trans" for trans flag on title card header thing

	- [?] Fix things for local mutliplayer
		- [?] Fix the whole shop system, it only works for the first player
			- [x] Fix the text
			- [?] Fix the detection of what item was bought where; it proritizes player 1's section
				- system works now kinda sorta
				- [ ] would probably be best to just re-do the whole thing with seperate event names for the different sections (i.e. EVENT1, EVENT2, COOL1, COOL2, etc.)
		- [?] Same goes for the costume/player doors
			- [ ] Replace the block shown underneath if the game is multiplayer. Or do it for both mp/sp.

	- [ ] Make a complete re-write of redCoins.lua
		- Bring down the amount of tables.
		- Use Misc.isPaused().

	- [ ] Change the coins in the HUD to reflect what coins are in the current level/section

	- [ ] Idea for a level: Temporary lava-walking boots

	- [ ] Level idea for the sky thing: "Skyfall", where you switch between ground and sky a few times
		- [ ] Try out some Sonic Lost World music for this?

	- [ ] Replace all the SMB3 Fire Flowers with SMB1 Fire Flowers, and vice versa, to get around the problem of the modern reserve system being Boned
		- [ ] Also swap the GFX around

	- [ ] Make slope GFX for the Super Mario Land stage

	- [ ] Have extra power-ups that don't get put in the reserve item slot give the player coins
		- [ ] Have a variable track the previous item slot; if it's the same, give the player coins. If not, do nothing.

	- [?] ENSURE THE HUD WORKS WITH MULTIPLAYER!

	- [ ] Play test each one of the levels with the other 3 characters
		- [ ] Make sure Peach can't exploit anything

	- [ ] Implement more costumes
		- See if there's any suitable ones, like SMB2 mario/luigi ones
		- see if there's literally any for toad lmao

	- [ ] Add more hidden goodies to levels
		- [ ] Add golden pipes to certain levels that gives the player a good amount of coins
			- Maybe make them one-time use? They disappear via global save.

	- Bring back the old 8-bit toad town idea, make that the third world?
		- Also have the same idea for "The Heisted Items" level; 8-bit toad town store is functionless until you retrieve the items back
		- One of the gimmicks for 8-bit toad town would be all levels have dragon coins
		- Move the cat mario level to 8-bit toad town
	- World idea: Ice world (original i know), but with snowy toad residents to chat up with!
	- Modify Star-Man to instead give the player coins on each kill
		- Make an indicator showing how many coins gaineds

	- Level with a giant clock in the background
		- just because i wanna flex os.time
		- also because of the second level in wario: master of disguise, that was cool

	- Use the current date to have special christmas effects happen
		- print(os.date("today is %A, in %B"))
		- Koopas get santa hats, and snow on shell ala the ice level


	IDEA: Hard Mode
		- Player gains twice as main coins in Hard Mode.
			- This stacks with the 2x coins power-up, if that's implemented.
		- Enemies become faster
			- Projectiles too
		- Bosses gain more health


Ideas from old README:
- Hint toad, one that you unlock hints for after collecting certain amounts of power stars, e.g. how to find the syobon action stage.
- Use Defines.gravity to set the gravity lower, e.g. to 6, for a Space level.
- Add a survival mini-game in a level, where shells are flying all over the place; the reward is a star for surviving it.
]]

gplayerData = {}

LevelsTable = {}

SaveData["episode"] = SaveData["episode"] or {}
globalsave = SaveData["episode"]

local function addLevel(tbl) -- level, name, world, starcoins, emblem
	table.insert(LevelsTable, tbl)
end

function SearchLevelName(level)
	for key, value in pairs(LevelsTable) do
		if LevelsTable[key].level == level then
			return LevelsTable[key]
		end
	end
end

local waterrun = require("Libraries.waterun")

textplus = require("textplus")
local scHUD = require("Libraries.scHUD")
scHUD.center1 = 626
scHUD.center2 = 768
scHUD.y = 32
scHUD.playery = 28
scHUD.offset = 16
scHUD.unclaimed = Graphics.loadImage(Misc.resolveFile("GFX/blue coin.png"))

GoodFont = textplus.loadFont("Fonts/Enjl/6.ini")
GoodFont2 = textplus.loadFont("Fonts/Enjl/5.ini")
GoodFont3 = textplus.loadFont("Fonts/Enjl/4.ini")
local TimeFont = textplus.loadFont("scripts/textplus/font/smb1-a.ini")

local anotherPowerDownLibrary = require("Libraries.anotherPowerDownLibrary")

local coyotetime = require("Libraries.coyotetime")
local ac = require("Libraries.anothercurrency")
myCurrency = ac.registerCurrency("Coins", true)
local ModernStyledHud = require("Libraries.ModernStyledHud")
ModernStyledHud.usetimelimit = false
local modernReserveItems = require("Libraries.modernReserveItems")
ffc = require("Libraries.FireFlowerCoins")

aw = require("Libraries/anotherwalljump")
aw.registerAllPlayersDefault()
aw.antilayername = "nowalljump"

coinFX = require("Libraries/coinFX")


addLevel{level = "1-1_.lvlx", name = "1-1?", world = 1, starcoins = 3, emblem = "GFX/TCE/upside.png"}
addLevel{level = "Sybono Action Level.lvlx", name = "???", world = 1, starcoins = 1, emblem = "GFX/TCE/cat.png"}
addLevel{level = "Shiverside.lvlx", name = "???", world = 1, starcoins = 1, emblem = "GFX/TCE/ice.png"}
addLevel{level = "New Sky Lake.lvlx", name = "Sky Lake", world = 1, starcoins = 1, emblem = "GFX/TCE/sky.png"}
addLevel{level = "New Carved Woodlands.lvlx", name = "Carved Woodlands", world = 1, starcoins = 2, emblem = "GFX/TCE/wood.png"}
addLevel{level = "Too Many Pipes!.lvlx", name = "Too Many Pipes!", world = 1, starcoins = 2, emblem = "GFX/TCE/pipe.png"}
addLevel{level = "SMB1 level.lvlx", name = "Koopa Mayhem", world = 1, starcoins = 3, emblem = "GFX/TCE/koopa.png"}
addLevel{level = "Forest level.lvlx", name = "Forage Forest", world = 1, starcoins = 1}
addLevel{level = "Volcanic Run.lvlx", name = "Volcanic Run", world = 1, emblem = "GFX/TCE/lava.png"}
addLevel{level = "Birdo's Revenge.lvlx", name = "???", world = 1, emblem = "GFX/TCE/birdos.png"}
--addLevel{level = "A World's Transition.lvlx", name = "???", world = 1}

if globalsave.DefeatBirdo then
	addLevel{level = "le tank.lvlx", name = "???", world = 2, starcoins = 2, emblem = "GFX/TCE/tank.png"}
	if globalsave.SaveTheTown then
		addLevel{level = "Ren Jungle.lvlx", name = "Factory Forest", world = 2, starcoins = 1, emblem = "GFX/TCE/factory.png"}
		addLevel{level = "Super Mario Land 2.lvlx", name = "???", world = 2}
		addLevel{level = "Twilight Forest.lvlx", name = "Dwindle Forest", world = 2, starcoins = 3, emblem = "GFX/TCE/dwindle.png"}
		addLevel{level = "Electric Hectics.lvlx", name = "Electric Hectics", world = 2, starcoins = 3, emblem = "GFX/TCE/electric.png"}
		addLevel{level = "Waterfall Haven.lvlx", name = "Waterfall Haven", world = 2, starcoins = 3, emblem = "GFX/TCE/waterfall.png"}
		addLevel{level = "Skyfall.lvlx", name = "Skyfall", world = 2}
		addLevel{level = "Boom Boom's Airship.lvlx", name = "???", world = 2}
		if globalsave.OpenCastle then
			-- Desert
			addLevel{level = "Water-Running.lvlx", name = "Technology Shores", world = 3, starcoins = 1}
			--addLevel{level = "Nintendosoft.lvlx", name = "Tendosoft Windows", world = 3, starcoins = 0}

			-- Snow
			addLevel{level = "ren 1.lvlx", name = "Cold Cave Climb", world = 4, starcoins = 1}
			addLevel{level = "Smoke Station.lvlx", name = "Smoke Station", world = 4}
		end
	end
end

addLevel{level = "Mario Castle.lvlx", name = "Hub World", world = 0}

UpgradesTable = {}

local function addUpgrade(tbl)
    table.insert(UpgradesTable, tbl)
end

addUpgrade{name = "Hard Mode", globalsave = "HardModePurchase"}
addUpgrade{name = "Costume Changer", globalsave = "CostumeChanger"}
addUpgrade{name = "Character Door", globalsave = "CharacterDoor"}
addUpgrade{name = "Second Item Slot", globalsave = "SecondItemSlot"}
addUpgrade{name = "Liquid Boots", globalsave = "WaterBoots"}

function CollectedUpgrades()
	local amnt = 0
	for index, value in ipairs(UpgradesTable) do
        if globalsave[value.globalsave] then
			amnt = amnt + 1
        end
    end
	return amnt
end

TotalStarCoins = 0

for key, value in pairs(LevelsTable) do
	if tonumber(value.starcoins) then
		TotalStarCoins = TotalStarCoins + value.starcoins
	end
end


--["idfk.lvlx"] = "Abridged Town",
--["Debug Room.lvlx"] = "Debug",

local Cheats = require("base/game/newcheats")
Cheats.register("trans", {
    onActivate = function()
        GameData.TransFlag = not GameData.TransFlag
        return true
    end,
    activateSFX = 34,
    isCheat = false
})
Cheats.register("pichu", {
    onActivate = function()
        GameData.PichuTime = not GameData.PichuTime
        return true
    end,
    activateSFX = 34,
    isCheat = false
})
Cheats.register("masuda", {
    onActivate = function()
        GameData.Masuda = not GameData.Masuda
        return true
    end,
    activateSFX = 34,
    isCheat = false
})


local TitleCard = require("Libraries/titlecard")
TitleCard.exceptions = {["Mario Castle.lvlx"] = true,
["idfk.lvlx"] = true,
}

local pausemenu = require("Libraries.pausemenu")

function changemoney(money, nosave)
	myCurrency._value = myCurrency._value + money
	if myCurrency._value < 0 then myCurrency._value = 0 end
	if not nosave then SaveData._anothercurrency.Coins = myCurrency._value end
end

local function SetPlayerValues(gayer, gtable)
	if not gtable[gayer.idx].setValues then
		gtable[gayer.idx].reservePowerup = globalsave["reservePowerup" .. gayer.idx] or 0
		gtable[gayer.idx].reservePowerupTwo = globalsave["reservePowerupTwo" .. gayer.idx] or 0
		gtable[gayer.idx].WaterShoesOn = globalsave["WaterShoesOn" .. gayer.idx] or false
		gtable[gayer.idx].setValues = true
	end
end

-- code by KBM-Quine
function checkLivingIndex()
    for k, p in ipairs(Player.get()) do
        if p.deathTimer == 0 and p:mem(0x13C, FIELD_BOOL) == false then
            return p.idx
        end
    end
end

function isAnyPlayerAlive()
    if checkLivingIndex() ~= nil then
        return true
    else
        return false
    end
end


function getCollectedStarCount(levelName) -- thanks to Bluenaxela/Rednaxela? for the code!
	local starCount = mem(0x00B251E0, FIELD_WORD)
    local starTablePtr = mem(0x00B25714, FIELD_DWORD)
    local counter = 0
    for starIdx=1,starCount do
        local starLevelName = tostring(mem(starTablePtr + (starIdx-1)*8, FIELD_STRING))
        local starSection = mem(starTablePtr + (starIdx-1)*8 + 4, FIELD_WORD)
        if (starLevelName == levelName) then
            counter = counter + 1
        end
    end
    return counter
end

local HardLayer
local NormalLayer


-- Run code on the first frame
function onStart()
	--globalsave.RestartOnDeath

	HardLayer = Layer.get("Hard Mode")
	NormalLayer = Layer.get("Normal Mode")
	globalsave.RestartOnDeath = globalsave.RestartOnDeath or false

	if not isOverworld then
        for _, p in ipairs(Player.get()) do
            gplayerData[p] = gplayerData[p] or {}
            gplayerData[p].curState = gplayerData[p].curState or 0
        end
    end
	for _,plyr in ipairs(Player.get()) do
		gplayerData[plyr.idx] = gplayerData[plyr.idx] or {}
		SetPlayerValues(plyr, gplayerData)
	end
	mem(0x00B2C5AC, FIELD_FLOAT, 5) -- set lives to 5, for "infinite" lives basically; also allows room to determine extra lives gained to convert to coins
	myCurrency._value = myCurrency.value
	if myCurrency._value == nil then
		myCurrency._value = 0
	end
	VisualCoins = myCurrency._value

	-- [[ Change level names depending on save progress ]] --
	if globalsave.DefeatBirdo then
		SearchLevelName("Birdo's Revenge.lvlx").name = "Birdo's Revenge"
		SearchLevelName("Birdo's Revenge.lvlx").emblem = "GFX/TCE/birdo.png"
	end
	if globalsave.Cat then
		SearchLevelName("Sybono Action Level.lvlx").name = "Syobon Action"
	end
	if globalsave.CompleteSML then
		SearchLevelName("Super Mario Land 2.lvlx").name = "Super Mario Land 2"
	end
	if globalsave.Pranked then
		SearchLevelName("Shiverside.lvlx").name = "Shiverside"
	end
	if globalsave.SaveTheTown then
		SearchLevelName("le tank.lvlx").name = "Boom Boom's Tank"
	end
	if globalsave.OpenCastle then
		SearchLevelName("Boom Boom's Airship.lvlx").name = "Boom Boom's Airship"
	end
	if not globalsave.HMLevelsBeat then
		globalsave.HMLevelsBeat = {}
	end
	if not globalsave.LevelsBeat then
		globalsave.LevelsBeat = {}
	end
	if not globalsave.WBHUD then
		globalsave.WBHUD = 1
	end
	if not globalsave.HardMode then
		globalsave.HardMode = false
	end

	if GameData.DeadPlayer or not globalsave.StartGameMushroom then
		if not globalsave.HardMode then
			for _,plyr in ipairs(Player.get()) do
				if plyr.powerup < PLAYER_BIG then
					plyr.powerup = PLAYER_BIG
				end
			end
		end
		GameData.DeadPlayer = false
		globalsave.StartGameMushroom = true
	end
end

PlayerIsDead = false
local NPCidxMinusOne = readmem(0x00B259E8, FIELD_DWORD) + 127*0x158

local ListOfPowerups = {
	[9] = 1, -- mushroom
	[184] = 1,
	[185] = 1,
	[249] = 1,

	[14] = 2, -- fire flower
	[182] = 2,
	[183] = 2,

	[264] = 2, -- ice flower
	[277] = 2,

	[34] = 3, -- leaf

	[169] = 4, -- tanooki
	[170] = 4, -- hammer suit
}


local function restart(plyr)
    if GameData.PlayerWarp > 0 then
        mem(0x00B2C6DA, FIELD_WORD, GameData.PlayerWarp)
    else
        mem(0x00B2C6DA, FIELD_WORD, -1)
    end
    mem(0x00B25720, FIELD_STRING, Level.filename());
    mem(0x00B250B4, FIELD_WORD, 0);
    mem(0x00B25134, FIELD_WORD, 0);
    mem(0x00B2C89C, FIELD_WORD, 0);
    mem(0x00B2C620, FIELD_WORD, 0);
    mem(0x00B2C5B4, FIELD_WORD, -1);
end

function onTick()
	-- [[ Testing Mode stuff ]] --
	if mem(0x00B2C624, FIELD_STRING) == "" then -- there isn't a "proper" way to detect test mode to my knowledge, this is the best i can do
		mem(0x00B251E0, FIELD_WORD, 70)
	end

	-- [[ Add level to (Hard Mode) beaten levels]] --
	if Level.winState() > 0 then
		if globalsave.HardMode and not globalsave.HMLevelsBeat[Level.filename()] then
			globalsave.HMLevelsBeat[Level.filename()] = true
		end
		if not globalsave.LevelsBeat[Level.filename()] then
			globalsave.LevelsBeat[Level.filename()] = true
		end
	end

    if not isOverworld then
        for _, p in ipairs(Player.get()) do
            gplayerData[p] = gplayerData[p] or {}
            gplayerData[p].curState = gplayerData[p].curState or 0
        end
    end

	-- [[ Hard Mode Layer Stuff ]] --
	if globalsave.HardMode then
		if HardLayer and HardLayer.isHidden then HardLayer:show(true) end
		if NormalLayer and not NormalLayer.isHidden then NormalLayer:hide(true) end
		anotherPowerDownLibrary.enabled = false
	else
		if HardLayer and not HardLayer.isHidden then HardLayer:hide(true) end
		if NormalLayer and NormalLayer.isHidden then NormalLayer:show(true) end
		anotherPowerDownLibrary.enabled = true
	end

	-- [[ Reserve Box Replacement ]] --
	for sin,plyr in ipairs(Player.get()) do
		gplayerData[plyr.idx] = gplayerData[plyr.idx] or {}
		SetPlayerValues(plyr, gplayerData)
		if globalsave["reservePowerup" .. plyr.idx] == nil then
			globalsave["reservePowerup" .. plyr.idx] = 0
		end
		if globalsave["reservePowerupTwo" .. plyr.idx] == nil then
			globalsave["reservePowerupTwo" .. plyr.idx] = 0
		end
		if globalsave["WaterShoesOn" .. plyr.idx] == nil then
			globalsave["WaterShoesOn" .. plyr.idx] = globalsave.WaterBoots or false
		end

		if globalsave["reservePowerup" .. plyr.idx] ~= gplayerData[plyr.idx].reservePowerup then
			globalsave["reservePowerup" .. plyr.idx] = gplayerData[plyr.idx].reservePowerup
		end
		if globalsave["reservePowerupTwo" .. plyr.idx] ~= gplayerData[plyr.idx].reservePowerupTwo then
			globalsave["reservePowerupTwo" .. plyr.idx] = gplayerData[plyr.idx].reservePowerupTwo
		end

		-- [[ Restart on Death ]] --
		if plyr.deathTimer == 199 and globalsave.RestartOnDeath
		and not isAnyPlayerAlive() then
			restart()
		end
	end

	-- [[ Convert extra lives to coins]] --
	if mem(0x00B2C5AC, FIELD_FLOAT) > 5 then
		local livesset = mem(0x00B2C5AC, FIELD_FLOAT) - 1
		mem(0x00B2C5AC, FIELD_FLOAT, livesset)
		if globalsave.HardMode then
			changemoney(100, true)
		else
			changemoney(50, true)
		end
	elseif mem(0x00B2C5AC, FIELD_FLOAT) < 5 then
		mem(0x00B2C5AC, FIELD_FLOAT, 5)
	end

	-- [[ fix for weird issue w/ moving layers and climbables, made by Enjl, "Quantumenace's Fence Bug Fix" ]] --
	writemem(NPCidxMinusOne+0x98, FIELD_DFLOAT, 0)
	writemem(NPCidxMinusOne+0xA0, FIELD_DFLOAT, 0)

	-- [[ Update Visual Coin Counter to match real one]] --
	if VisualCoins ~= myCurrency._value then
		if VisualCoins > myCurrency._value then
			VisualCoins = VisualCoins - 1
		elseif VisualCoins < myCurrency._value then
			VisualCoins = VisualCoins + 1
		end
	end

	-- [[ Save Data 2 Game Data Variables, for the loading screen ]] --
	GameData.HardMode = globalsave.HardMode
	GameData.HardModePurchase = globalsave.HardModePurchase
	GameData.HMLevelsBeat = globalsave.HMLevelsBeat
	GameData.LevelsTable = LevelsTable
end

function onTickEnd()
	for _,plyr in ipairs(Player.get()) do
		if plyr.reservePowerup > 0 then
			if gplayerData[plyr.idx].reservePowerup == 0 then
				gplayerData[plyr.idx].reservePowerup = plyr.reservePowerup
			elseif ListOfPowerups[plyr.reservePowerup] ~= 1 then
				if globalsave.SecondItemSlot then
					gplayerData[plyr.idx].reservePowerupTwo = gplayerData[plyr.idx].reservePowerup
				end
				gplayerData[plyr.idx].reservePowerup = plyr.reservePowerup
			elseif globalsave.SecondItemSlot and (ListOfPowerups[plyr.reservePowerup] == 1 and gplayerData[plyr.idx].reservePowerupTwo == 0) then
				gplayerData[plyr.idx].reservePowerupTwo = plyr.reservePowerup
			end
			plyr.reservePowerup = 0
		end
		if gplayerData[plyr.idx].reservePowerup == 0 and gplayerData[plyr.idx].reservePowerupTwo > 0 then
			gplayerData[plyr.idx].reservePowerup = gplayerData[plyr.idx].reservePowerupTwo
			gplayerData[plyr.idx].reservePowerupTwo = 0
		end
		if gplayerData[plyr.idx].reservePowerupTwo > 0 and not globalsave.SecondItemSlot then
			gplayerData[plyr.idx].reservePowerupTwo = 0
		end
	end
end

function onPlayerKill(eventObj, harmedPlayer)
   if globalsave.LifeSaver then
	   if harmedPlayer.y >= harmedPlayer.sectionObj.boundary.bottom + 64 then
			eventObj.cancelled = true
			harmedPlayer.speedY = -23
			SFX.play(35)
			harmedPlayer:mem(0x140, FIELD_WORD, 39)
			if harmedPlayer == player then -- only affects player 1
				globalsave.LifeSaver = false
			end
			harmedPlayer.harmtime = true
		end
	end
end

function onPostPlayerKill(harmedPlayer)
	if player == harmedPlayer then
		if myCurrency._value >= 10 then
			if globalsave.HardMode then
				coinFX.AddCoin(5)
			else
				coinFX.AddCoin(3)
			end
		elseif myCurrency._value > 0 then
			coinFX.AddCoin(1)
		end
		if globalsave.HardMode then
			changemoney(-20, true)
		else
			changemoney(-10, true)
		end
		GameData.DeadPlayer = true
		PlayerIsDead = true -- just to make sure the star counter doesn't show up
	else -- player 2 or clone died, ensure less suffering
		if myCurrency._value > 0 then
			coinFX.AddCoin(1)
		end
		changemoney(-3, true)
	end
	SaveData._anothercurrency.Coins = myCurrency._value
end

-- Run code when internal event of the SMBX Engine has been triggered
-- eventName - name of triggered event
function onEvent(eventName)

end

local HardModeGFX = Graphics.loadImage(Misc.resolveFile("GFX/hard mode low-res incomplete.png"))
local HardModeGFX2 = Graphics.loadImage(Misc.resolveFile("GFX/hard mode low-res.png"))

local WarpTable = {}
function onDraw()
	for _,plyr in ipairs(Player.get()) do
		-- [[ Replace Star Counter ]] --
		if plyr:mem(0x5A,FIELD_WORD) > 0 then
			local warp = Warp(plyr:mem(0x5A,FIELD_WORD)-1)
			if warp:mem(0x8C, FIELD_WORD) > 0 then
				local InsertToWarp = {}
				InsertToWarp.name = warp.levelFilename
				InsertToWarp.stars = warp:mem(0x8A, FIELD_WORD)
				InsertToWarp.totalstars = warp:mem(0x8C, FIELD_WORD)
				warp:mem(0x8C, FIELD_WORD, 0)
				table.insert(WarpTable, InsertToWarp)
			else
				for key, value in pairs(WarpTable) do
					if WarpTable[key].name == warp.levelFilename then
						textplus.print{
							sceneCoords = true,
							x = plyr.x,
							y = plyr.y + -37,
							pivot = {0.5, 0.5},
							text = "<size 2> 🌟 ✕ " .. WarpTable[key].stars .. "/ " .. WarpTable[key].totalstars .. "</size>",
							font = GoodFont
						}
					end
				end
			end
		end
		-- [[ Display Level Name Above Star Counter ]] --
		if plyr:mem(0x5A,FIELD_WORD) > 0 then
			local warp = Warp(plyr:mem(0x5A,FIELD_WORD)-1)
			if warp.levelFilename ~= "" then
				local PreText = "<size 2><wave 2>"
				local PostText = "</wave></size>"
				--[[if globalsave.LevelsBeat[warp.levelFilename] then
					PreText = "<size 2>"
					PostText = "</size>"
				end]]
				textplus.print{
					sceneCoords = true,
					x = plyr.x + 13,
					y = plyr.y + -56, -- YOffset
					pivot = {0.5, 0.5},
					text = PreText .. tostring(SearchLevelName(warp.levelFilename).name) .. PostText,
					font = GoodFont
				}
				-- [[ Display Hard Mode indicator above level name ]] --
				if globalsave.HardModePurchase then
					local Gamer = HardModeGFX -- i am so sorry for this variable name
					if globalsave.HMLevelsBeat[warp.levelFilename] then
						Gamer = HardModeGFX2
					end
					Graphics.drawImageToScene(Gamer, plyr.x + (plyr.width/2) - (Gamer.width/2), plyr.y - 88, 0.8)
				end
			end
		end

	end
end